package com.kaida.kaidaquery.service;

import com.kaida.kaidaquery.exception.QueryException;
import org.apache.commons.io.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zxm
 * @date 2020/9/19 18:52
 */

@Service
public class ServiceImpl {


    private static final String URL_QUERY_PATH = "http://www2.kfu.edu.cn/zs/index.php/home/student/lqcx.html";
    private static final String rgex = "<div class=\"layui-form-mid\">(.*?)</div>";
    private static final String exists = "<div class=\"message\">(.*?)</div>";

    /**
     * 简单查询
     *
     * @return
     */
    public String query(String name, String authKey) throws Exception {
        return getMajor(name, authKey);
    }

    private String getMajor(String name, String authKey) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(URL_QUERY_PATH);
        Header header = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addHeader(header);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("name", name));
        nameValuePairs.add(new BasicNameValuePair("idcard", authKey));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "utf-8");
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String respStr = EntityUtils.toString(response.getEntity());
            return analysis(respStr);
        } else {
            throw new Exception("request fail");
        }
    }

    private static String analysis(String str) throws Exception {
        str = str.replace("\r\n", "");
        Pattern pattern = Pattern.compile(exists);
        Matcher m = pattern.matcher(str);
        if (m.find()) {
            throw new QueryException(m.group(1));
        }
        pattern = Pattern.compile(rgex);
        m = pattern.matcher(str);
        int i = 1;
        while (m.find()) {
            if (i == 4) {
                return m.group(1).trim();
            }
            i++;
        }
        throw new Exception("request fail");
    }
}
